<script setup lang="ts">
import { ProjectForm } from '@/api/exam/project/types';
import { listAnswer } from '@/api/exam/answer';
import { AnswerVO } from '@/api/exam/answer/types';
import * as echarts from 'echarts';
import { EChartsOption } from 'echarts';

interface Props {
  projectForm: any | ProjectForm;
}

const props = withDefaults(defineProps<Props>(), {
  projectForm: {
    survey: {
      children: []
    }
  }
});
const projectForm = ref<ProjectForm>(props.projectForm);
watch(() => props.projectForm, () => {
  projectForm.value = props.projectForm;
});
const answerList = ref<AnswerVO[]>([]);
const queryParams = ref<any>({
  projectId: projectForm.value.id,
  tempSave: '1'
});
const getAnswerList = async () => {
  const res = await listAnswer(queryParams.value);
  answerList.value = res.data;
};
const getAverageCompletion = () => {
  let temp = 0;
  answerList.value.forEach((item) => {
    temp += (Date.parse(item.metaInfo['answerInfo'].endTime) - Date.parse(item.metaInfo['answerInfo'].startTime)) / 1000;
  });
  temp = temp / answerList.value.length;
  return formatTimeDifference(temp);
};

function formatTimeDifference(seconds) {
  // 确保输入是数字类型
  seconds = parseFloat(seconds);

  // 处理小于0的情况
  if (isNaN(seconds) || seconds < 0) {
    return '0秒';
  }

  // 计算分钟和剩余秒数
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);

  // 确保秒数始终显示为两位数字
  const formattedSeconds = remainingSeconds < 10 ?
    `0${remainingSeconds}` :
    remainingSeconds;

  return `${minutes} 分 ${formattedSeconds} 秒`;
}

// 收集情况
const dateCountMap = {};
const dateList = ref();
const countList = ref();

// 平台类型
const platformCountMap = {};
const platformList = ref();

const chart = ref();
let myChart: any;
const getData = async () => {
  answerList.value.forEach(item => {
    let endTime = item.metaInfo['answerInfo'].endTime;
    if (endTime) {
      // 提取日期部分（保留到日）
      let date = endTime.split(' ')[0];  //
      // 统计数量
      dateCountMap[date] = (dateCountMap[date] || 0) + 1;
    }
    if (item.metaInfo['clientInfo'].platform) {
      platformCountMap[item.metaInfo['clientInfo'].platform] = (platformCountMap[item.metaInfo['clientInfo'].platform] || 0) + 1;
    }
  });
  // 提取日期列表并排序
  dateList.value = Object.keys(dateCountMap).sort();
  // 提取对应的数量列表
  countList.value = dateList.value.map(date => dateCountMap[date]);
  platformList.value = Object.entries(platformCountMap).map(([key, value]) => ({ name: key, value }));

  getDataChart();
  getPlatformData();
};
const getDataChart = () => {
  let infoEl = chart.value;
  myChart = echarts.init(infoEl);
  // myChart.value = echarts.init(chart.value); // 重新初始化图表实例

  let option: EChartsOption;
  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: 'rgba(106,121,133,0.42)'
        }
      }

    },
    legend: {
      data: ['份']
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    title: {},
    grid: {
      left: '2%',
      right: '2%',
      top: '10%',
      bottom: '0%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dateList.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '份',
        type: 'line',
        smooth: true,
        stack: 'Total',
        // symbolSize: 8,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 0.9, [
            {
              offset: 0,
              // color: 'rgba(58,77,233,0.8)'
              color: 'rgba(170, 201 ,234,0.8)'
            },
            {
              offset: 1,
              // color: 'rgba(58,77,233,0)'
              color: 'rgba(170, 201 ,234,0)'
            },
            {
              offset: 0,
              color: 'rgba(170, 201 ,234,1)'
              // color: 'rgba(58,77,233,0.9)'
            }
          ])
        },
        itemStyle: {
          // color: "#3D5DF4",
          color: '#4EA6FE'
        },
        lineStyle: {
          // 线条加阴影
          // 设置阴影颜色
          // shadowColor: "#3D5DF4",
          shadowColor: '#4EA6FE',
          shadowOffsetX: 0,
          // 设置阴影沿y轴偏移量为9
          shadowOffsetY: 9,
          // 设置阴影的模糊大小
          shadowBlur: 10,
          // 设置线条渐变色
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#94C2FD00' },
            // { offset: 0.2, color: "#3D5DF4" },
            { offset: 0.2, color: '#4EA6FE' },
            { offset: 0.1, color: '#5B8FF900' }
          ])
        },
        data: countList.value
      }
    ]
  };

  myChart.resize(); // 调整图表大小
  option && myChart.setOption(option); // 设置图表选项
};
let platformChart: any;
const chart2 = ref();
const getPlatformData = () => {
  platformChart = echarts.init(chart2.value); // 重新初始化图表实例
  let option: EChartsOption;
  option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',  // 设置图例垂直显示
      top: '5%',           // 设置图例顶部位置
      left: 'left',        // 设置图例显示在左侧
      formatter: (name) => {
        return name;
      },
      tooltip: {
        show: true
      }
    },
    series: [
      {
        name: '常用系统',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        padAngle: 5,
        itemStyle: {
          borderRadius: 20
        },
        label: {
          show: false,
          position: 'center'
        },
        labelLine: {
          show: false
        },
        data: platformList.value
      }
    ]
  };

  platformChart.resize(); // 调整图表大小
  option && platformChart.setOption(option); // 设置图表选项

};
onMounted(async () => {
  await getAnswerList();
  await getData();
});
</script>

<template>
  <a-flex vertical gap="middle" style="flex: 1;overflow-y: auto;padding: 0 40px">
    <a-flex justify="space-between" class="p-5">
      <span class="header-title">{{ projectForm.name }}</span>
      <a-descriptions layout="vertical" style="max-width:250px">
        <a-descriptions-item label="数据量">{{ answerList.length }}</a-descriptions-item>
        <a-descriptions-item label="平均完成时间">{{ getAverageCompletion() }}</a-descriptions-item>
      </a-descriptions>
    </a-flex>
    <a-card hoverable style="width: 100%">
      <template #title>
        <div class="card-title">收集情况</div>
      </template>
      <div>
        <div ref="chart" style="height: 300px"></div>
      </div>
    </a-card>
    <a-row>
      <a-col :span="6">
        <a-card hoverable>
          <template #title>
            <div class="card-title">常用系统</div>
          </template>
          <div ref="chart2" style="height: 280px"></div>
        </a-card>
      </a-col>
    </a-row>

  </a-flex>

</template>

<style scoped lang="scss">
.header-title {
  font-weight: 600;
  font-size: 30px;
  line-height: 48px;
  flex: 1 1;
}
</style>
